<template>

  <div class="login-container">
   
           <div class="login-container">
             <img src="https://img1.dxycdn.com/p/s12/2024/0808/296/6735449000820741281.png" alt="Login Left Decor" class="left-decor-img" />
          </div>

      <div class="login-box">
          <div class="logo">
              <img src="https://img1.dxycdn.com/t/s22/2023/1020/192/0844255084588925171.png" alt="丁香医生" class="logo-img" />
          </div>
          
          <div class="login-tabs">
              <span 
                  :class="['tab', { active: loginType === 'sms' }]"
                  @click="loginType = 'sms'"
              >短信登录</span>
              <span 
                  :class="['tab', { active: loginType === 'password' }]"
                  @click="loginType = 'password'"
              >密码登录</span>
          </div>

          <form @submit.prevent="handleLogin" class="login-form">
              <template v-if="loginType === 'sms'">
                  <div class="form-group">
                      <input 
                          type="tel" 
                          v-model="formData.phone" 
                          placeholder="手机号"
                          class="input-field"
                          maxlength="11"
                      />
                  </div>
                  <div class="form-group verification-group">
                      <input 
                          type="text" 
                          v-model="formData.code" 
                          placeholder="验证码"
                          class="input-field"
                          maxlength="6"
                      />
                      <button 
                          class="get-code-btn" 
                          @click="startCountdown"
                          :disabled="countdown > 0"
                      >
                          {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                      </button>
                  </div>
              </template>
              
              <template v-else>
                  <div class="form-group">
                      <input 
                          type="text" 
                          v-model="formData.username" 
                          placeholder="用户名/手机号/邮箱"
                          class="input-field"
                      />
                  </div>
                  <div class="form-group">
                      <input 
                          :type="showPassword ? 'text' : 'password'" 
                          v-model="formData.password" 
                          placeholder="密码"
                          class="input-field"
                      />
                      <span 
                      class="toggle-password"
                      @click="showPassword = !showPassword"
                      :title="showPassword ? '隐藏密码' : '显示密码'"
                  >
                      <svg v-if="showPassword" class="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M12 4.5C7 4.5 2.73 7.61 1 12C2.73 16.39 7 19.5 12 19.5C17 19.5 21.27 16.39 23 12C21.27 7.61 17 4.5 12 4.5ZM12 17C9.24 17 7 14.76 7 12C7 9.24 9.24 7 12 7C14.76 7 17 9.24 17 12C17 14.76 14.76 17 12 17ZM12 9C10.34 9 9 10.34 9 12C9 13.66 10.34 15 12 15C13.66 15 15 13.66 15 12C15 10.34 13.66 9 12 9Z" fill="currentColor"/>
                      </svg>
                      <svg v-else class="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M12 6.5C15.79 6.5 19.17 8.63 20.82 12C19.17 15.37 15.79 17.5 12 17.5C8.21 17.5 4.83 15.37 3.18 12C4.83 8.63 8.21 6.5 12 6.5ZM12 4.5C7 4.5 2.73 7.61 1 12C2.73 16.39 7 19.5 12 19.5C17 19.5 21.27 16.39 23 12C21.27 7.61 17 4.5 12 4.5ZM12 9.5C13.38 9.5 14.5 10.62 14.5 12C14.5 13.38 13.38 14.5 12 14.5C10.62 14.5 9.5 13.38 9.5 12C9.5 10.62 10.62 9.5 12 9.5ZM12 7.5C9.52 7.5 7.5 9.52 7.5 12C7.5 14.48 9.52 16.5 12 16.5C14.48 16.5 16.5 14.48 16.5 12C16.5 9.52 14.48 7.5 12 7.5Z" fill="currentColor"/>
                          <path d="M2 4L22 20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                      </svg>
                  </span>
                  </div>
              </template>

              <div class="agreement">
                  <label class="checkbox-label">
                      <input type="checkbox" v-model="agreed" />
                      <span>我已阅读并接受丁香园</span>
                      <a href="https://3g.dxy.cn/newh5/view/rule/userAgreement" target="_blank" class="link">《用户协议》</a>
                      <a href="https://3g.dxy.cn/newh5/view/rule/privacyPolicy" target="_blank" class="link">《隐私政策》</a>
                  </label>
              </div>

              <button type="submit" class="submit-btn" :disabled="!agreed || loading">
                  {{ loading ? '登录中...' : '登录' }}
              </button>

              <div class="bottom-links">
                  <a href="#" class="forgot-password">忘记密码？</a>
                  <router-link to="/res" class="register-link">注册新账号</router-link>
              </div>

              <div class="social-login">
                  <div class="wechat-login">
                      <img src="https://img1.dxycdn.com/p/s2/2024/0731/707/8026678031800568181.png" alt="微信" class="wechat-icon" />
                      <span>社交账号登录</span>
                  </div>
              </div>
          </form>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loginType = ref('sms')
const showPassword = ref(false)
const agreed = ref(false)
const loading = ref(false)
const countdown = ref(0)
let timer: number | null = null; // Use number for browser


const formData = reactive({
  phone: '',  
  code: '',
  username: '',
  password: ''
})

const startCountdown = () => {
    countdown.value = 60; // Start countdown at 60 seconds
    timer = window.setInterval(() => { // Explicitly use window.setInterval
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            clearTimer();
        }
    }, 1000);
};

const clearTimer = () => {
    if (timer !== null) {
        clearInterval(timer); // Clear the timer
        timer = null; // Reset the timer variable
    }
};

const getVerificationCode = async () => {
  if (!formData.phone) {
      ElMessage.warning('请输入手机号')
      return
  }
  
  if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
  }

  try {
      const response = await axios.get(`http://127.0.0.1:8000/user/userphonecode/${formData.phone}/`)
      if (response.status === 200) {
          ElMessage.success('验证码发送成功')
          startCountdown()
      }
  } catch (error: any) {
      ElMessage.error(error.response?.data?.error || '验证码发送失败')
  }
}

const handleLogin = async () => {
  if (!agreed.value) {
      ElMessage.warning('请先同意用户协议和隐私政策')
      return
  }

  try {
      loading.value = true
      if (loginType.value === 'sms') {
          const response = await axios.post('http://127.0.0.1:8000/user/usercode/', {
            phone: formData.phone,
            code: formData.code
          })
          console.log(response)
          
          
          if (response.status === 200) {
              const  access  = response.data.data.token
              localStorage.setItem('token', access)
              
              localStorage.setItem('userid',response.data.data.id) 
              ElMessage.success('登录成功')
              router.push('/')
          }
      } else {
          const response = await axios.post('http://127.0.0.1:8000/user/user/', {
              username: formData.username,
              password: formData.password
          })
          
          if (response.status === 200) {
              const  access   = response.data.data.token
              localStorage.setItem('token','Bearer '+access)
              
        
              localStorage.setItem('userid',response.data.data.id)
              ElMessage.success('登录成功')
              router.push('/')
          }
      }
  } catch (error: any) {
      ElMessage.error(error.response?.data?.error || '登录失败')
  } finally {
      loading.value = false
  }
}
</script>

<style scoped>
  


.left-decor-img {
  /* 设置图片高度，可根据实际需求调整 */
  height: 500px;
  /* 使图片垂直居中 */
  vertical-align: middle;
  /* 设置图片显示模式为适应容器，保持宽高比 */
  object-fit: contain;
  /* 让图片左浮动，使其与右侧div内容在同一行显示 */
  float: left;
  /* 根据实际情况调整图片与右侧div内容的间距 */
  margin-right: 2px;
  
}


.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  padding: 0px;
}

.login-box {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  padding: 32px;
}

.logo {
  text-align: center;
  margin-bottom: 24px;
}

.logo-img {
  height: 40px;
}

.eye-icon {
  width: 20px;
  height: 20px;
}

.login-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
  gap: 32px;
}

.tab {
  font-size: 16px;
  color: #666;
  cursor: pointer;
  padding-bottom: 8px;
  position: relative;
}

.tab.active {
  color: #7B66FF;
  font-weight: 500;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #7B66FF;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  position: relative;
}

.input-field {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
}

.input-field:focus {
  border-color: #7B66FF;
  outline: none;
}

.verification-group {
  display: flex;
  gap: 12px;
}

.get-code-btn {
  white-space: nowrap;
  padding: 0 16px;
  color: #7B66FF;
  background: none;
  border: none;
  cursor: pointer;
}

.get-code-btn:disabled {
  color: #909399;
  cursor: not-allowed;
}

.toggle-password {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: pointer;
  font-size: 14px;
}

.agreement {
  font-size: 14px;
  color: #666;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.link {
  color: #7B66FF;
  text-decoration: none;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #7B66FF;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:disabled {
  background-color: #b2b2b2;
  cursor: not-allowed;
}

.bottom-links {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.forgot-password, .register-link {
  color: #666;
  text-decoration: none;
}

.social-login {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.wechat-login {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
  cursor: pointer;
}

.wechat-icon {
  width: 24px;
  height: 24px;
}
</style>